﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XgPushTest
{
    public static class Common
    {
        /// <summary>
        /// POST方式请求Webservice方法，地址："http://localhost:5320/WebService1.asmx/HelloWorld"，其中HelloWorld为请求的web方法
        /// </summary>
        /// <param name="url">请求的web服务地址</param>
        /// <param name="sendData">发送的数据</param>
        /// <returns></returns>
        public static string HttpConnectToServer(string url, string sendData)
        {
            //string postData = "strXml=" + strXml + "&strData=" + strData;
            byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
            //创建请求
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = dataArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            //创建输入流
            System.IO.Stream dataStream = null;
            try
            {
                dataStream = request.GetRequestStream();
            }
            catch (Exception)
            {
                return null;//连接服务器失败
            }
            //发送请求
            dataStream.Write(dataArray, 0, dataArray.Length);
            dataStream.Close();
            //读取返回消息
            string res = string.Empty;
            try
            {
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                res = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
                return null;//连接服务器失败
            }
            return res;
        }
    }
}
